﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Configuration;
using System.Drawing;
using System.Drawing.Design;
using System.IO;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace Extra.Windows.Forms
{
	internal static class WindowsFormsUtils
	{
		public static string GetComponentName(IComponent component, string defaultNameValue)
		{
			string name = string.Empty;
			if (string.IsNullOrEmpty(defaultNameValue))
			{
				if (component.Site != null)
					name = component.Site.Name;
				if (name == null)
					name = string.Empty;
				return name;
			}
			return defaultNameValue;
		}
	}

	internal class ImageListIndexer
	{
		private int index = -1;
		private string key = string.Empty;
		private bool useIntegerIndex = true;
		private object owner;
		private System.Reflection.PropertyInfo propInfo;

		public ImageListIndexer() { }

		public ImageListIndexer(object owner, string imageListPropertyName)
		{
			SetImageListOwner(owner, imageListPropertyName);
		}

		public void SetImageListOwner(object owner, string imageListPropertyName)
		{
			this.owner = owner;
			if (this.owner != null)
			{
				propInfo = this.owner.GetType().GetProperty(imageListPropertyName, typeof(ImageList));
				if (propInfo == null)
					throw new ArgumentException("Unable to locate ImageList property", "imageListPropertyName");
			}
			else
				propInfo = null;
		}

		public int ActualIndex
		{
			get
			{
				if (this.useIntegerIndex)
					return this.Index;
				if (this.ImageList != null)
					return this.ImageList.Images.IndexOfKey(this.Key);
				return -1;
			}
		}

		public ImageList ImageList
		{
			get
			{
				if (owner == null)
					return null;
				return propInfo.GetValue(owner, null) as ImageList;
			}
		}

		public int Index
		{
			get { return this.index; }
			set
			{
				this.key = string.Empty;
				this.index = value;
				this.useIntegerIndex = true;
			}
		}

		public string Key
		{
			get { return this.key; }
			set
			{
				this.index = -1;
				this.key = (value == null) ? string.Empty : value;
				this.useIntegerIndex = false;
			}
		}
	}


	[ToolboxItem(false), DesignTimeVisible(false), DefaultProperty("Text")]
	public class XColumnHeader : Component, ICloneable
	{
		private int displayIndex;
		internal int index;
		private XListView listview;
		internal string name;
		internal string text;
		private HorizontalAlignment textAlign;
		private bool textAlignInitialized;
		internal int width;
		public ContextMenuStrip dropDownContextMenu;
		public string format;
		public IFormatProvider formatProvider;
		public bool hideable = true;
		public string nullValue;
		public bool showDropDownButton = false;
		public bool sortable = true;
		public SortOrder sortOrder = SortOrder.None;
		private ImageListIndexer imageIndexer = new ImageListIndexer();

		public XColumnHeader()
		{
		}

		public XColumnHeader(int imageIndex)
		{
		}

		public XColumnHeader(string imageKey)
		{
		}

		internal void UpdateColumnInfo(NativeMethods.ListViewColumMask mask)
		{
			if ((this.ListView != null) && this.ListView.IsHandleCreated)
				this.ListView.SetColumnInfo(mask, this);
		}

		[Localizable(true)]
		public new int DisplayIndex
		{
			get { return this.displayIndex; }
			set
			{
				this.displayIndex = value;
				// TODO: resort all columns to accommodate this index
			}
		}

		[DefaultValue((String)null)]
		public ContextMenuStrip DropDownContextMenu { get; set; }

		[DefaultValue(true)]
		public bool Hideable
		{
			get { return this.hideable; }
			set { this.hideable = value; UpdateColumnInfo(NativeMethods.ListViewColumMask.Fmt); }
		}

		[TypeConverter(typeof(ImageIndexConverter)), Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(System.Drawing.Design.UITypeEditor)), DefaultValue(-1), RefreshProperties(RefreshProperties.Repaint), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public int ImageIndex
		{
			get
			{
				if (((this.imageIndexer.Index != -1) && (this.ImageList != null)) && (this.imageIndexer.Index >= this.ImageList.Images.Count))
					return (this.ImageList.Images.Count - 1);
				return this.imageIndexer.Index;
			}
			set
			{
				if (value < -1)
					throw new ArgumentOutOfRangeException("ImageIndex");
				if (this.imageIndexer.Index != value)
				{
					this.imageIndexer.Index = value;
					UpdateColumnInfo(NativeMethods.ListViewColumMask.Image);
				}
			}
		}

		[DefaultValue(""), Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(System.Drawing.Design.UITypeEditor)), RefreshProperties(RefreshProperties.Repaint), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), TypeConverter(typeof(ImageKeyConverter))]
		public string ImageKey
		{
			get { return this.imageIndexer.Key; }
			set
			{
				if (value != this.imageIndexer.Key)
				{
					this.imageIndexer.Key = value;
					UpdateColumnInfo(NativeMethods.ListViewColumMask.Image);
				}
			}
		}

		[Browsable(false)]
		public ImageList ImageList
		{
			get { return this.imageIndexer.ImageList; }
		}

		[Browsable(false)]
		public int Index { get { return (this.ListView != null) ? this.ListView.Columns.IndexOf(this) : -1; } }

		[Browsable(false)]
		public XListView ListView
		{
			get { return this.listview; }
			internal set
			{
				int width = this.Width;
				this.listview = value;
				this.Width = width;
				this.imageIndexer.SetImageListOwner(value, "SmallImageList");
			}
		}

		[Description("Name"), Browsable(false)]
		public string Name
		{
			get { return WindowsFormsUtils.GetComponentName(this, this.name); }
			set
			{
				this.name = (value == null) ? String.Empty : value;
				if (this.Site != null)
					this.Site.Name = value;
			}
		}

		[Description("Tag"), Category("Data"), Localizable(false), Bindable(true), DefaultValue((string) null), TypeConverter(typeof(StringConverter))]
		public object Tag { get; set; }

		[Description("Text"), Localizable(true)]
		public string Text
		{
			get
			{
				if (this.text == null)
					return "ColumnHeader";
				return this.text;
			}
			set
			{
				this.text = (value == null) ? String.Empty : value;
				UpdateColumnInfo(NativeMethods.ListViewColumMask.Text);
			}
		}

		[Localizable(true), Description("ColumnAlignment"), DefaultValue(0)]
		public HorizontalAlignment TextAlign
		{
			get
			{
				if (!this.textAlignInitialized && (this.listview != null))
				{
					this.textAlignInitialized = true;
					if (((this.Index != 0) && (this.listview.RightToLeft == RightToLeft.Yes)) && !this.listview.IsMirrored)
						this.textAlign = HorizontalAlignment.Right;
				}
				return this.textAlign;
			}
			set
			{
				if ((this.Index == 0) && (value != HorizontalAlignment.Left))
					value = HorizontalAlignment.Left;
				if (this.textAlign != value)
				{
					this.textAlign = value;
					UpdateColumnInfo(NativeMethods.ListViewColumMask.Fmt);
				}
			}
		}

		[Localizable(true), DefaultValue(60), Description("ColumnWidth")]
		public int Width
		{
			get
			{
				if (((this.listview != null) && this.listview.IsHandleCreated) && (!this.listview.Disposing && (this.listview.View == View.Details)))
				{
					IntPtr handle = NativeMethods.SendMessage(this.listview.Handle, (uint)NativeMethods.ListViewMessage.GetHeader);
					if (handle != IntPtr.Zero)
					{
						int num = (int)NativeMethods.SendMessage(handle, (uint)NativeMethods.HeaderMessage.GetItemCount);
						if (this.Index < num)
							this.width = NativeMethods.SendMessage(this.listview.Handle, (uint)NativeMethods.ListViewMessage.GetColumnWidth, this.Index).ToInt32();
					}
				}
				return this.width;
			}
			set
			{
				this.width = value;
				if (this.listview != null)
					this.listview.SetColumnWidth(this.Index, ColumnHeaderAutoResizeStyle.None);
			}
		}

		[DefaultValue(false)]
		public bool ShowDropDownButton
		{
			get { return this.showDropDownButton; }
			set
			{
				this.showDropDownButton = value;
				if (this.ListView != null)
					this.ListView.SetColumnDropDown(this.Index, value);
			}
		}

		[DefaultValue(true)]
		public bool Sortable
		{
			get { return this.sortable; }
			set { this.sortable = value; }
		}

		[DefaultValue(0)]
		public SortOrder SortOrder
		{
			get { return this.sortOrder; }
			set { this.sortOrder = value; }
		}

		internal NativeMethods.ListViewColumnFormat FormatFlags
		{
			get
			{
				NativeMethods.ListViewColumnFormat val = (NativeMethods.ListViewColumnFormat)this.textAlign;
				if (imageIndexer.ActualIndex != -1)
					val |= NativeMethods.ListViewColumnFormat.Image;
				if (imageAlign == LeftRightAlignment.Right)
					val |= NativeMethods.ListViewColumnFormat.BitmapOnRight;
				if (fixedWidth)
					val |= NativeMethods.ListViewColumnFormat.FixedWidth;
				if (showDropDownButton)
					val |= NativeMethods.ListViewColumnFormat.SplitButton;
				return val;
			}
		}

		public object Clone()
		{
			throw new NotImplementedException();
		}
	}

	[ListBindable(false), XmlRoot("Columns"), SettingsSerializeAs(SettingsSerializeAs.Xml), Serializable]
	public class XColumnHeaderCollection : List<XColumnHeader>, IXmlSerializable
	{
		System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
		{
			return null;
		}

		void IXmlSerializable.ReadXml(System.Xml.XmlReader reader)
		{
			reader.MoveToContent();
			int count = Convert.ToInt32(reader.GetAttribute("Count"));
			if (count == this.Count)
			{
				for (int i = 0; i < count; i++)
				{
					reader.ReadStartElement("Column");
					string attr = reader.GetAttribute("DisplayIndex");
					if (!string.IsNullOrEmpty(attr))
						this[i].DisplayIndex = Convert.ToInt32(attr);
					attr = reader.GetAttribute("Width");
					if (!string.IsNullOrEmpty(attr))
						this[i].Width = Convert.ToInt32(attr);
					attr = reader.GetAttribute("SortOrder");
					if (!string.IsNullOrEmpty(attr))
						this[i].SortOrder = (SortOrder)Enum.Parse(typeof(SortOrder), attr);
					reader.ReadEndElement();
				}
			}
		}

		void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
		{
			writer.WriteAttributeString("Count", this.Count.ToString());
			for (int i = 0; i < this.Count; i++)
			{
				writer.WriteStartElement("Column");
				writer.WriteAttributeString("Index", i.ToString());
				if (this[i].DisplayIndex != -1)
					writer.WriteAttributeString("DisplayIndex", this[i].DisplayIndex.ToString());
				writer.WriteAttributeString("Width", this[i].Width.ToString());
				if (this[i].SortOrder != SortOrder.None)
					writer.WriteAttributeString("SortOrder", this[i].SortOrder.ToString());
				writer.WriteEndElement();
			}
		}
	}

	internal class XColumnHeaderCollectionEditor : CollectionEditor
	{
		public XColumnHeaderCollectionEditor(Type type) : base(type)
		{
		}

		protected override string HelpTopic
		{
			get { return "net.ComponentModel.ColumnHeaderCollectionEditor"; }
		}

		protected override Type CreateCollectionItemType()
		{
			return typeof(XColumnHeader);
		}

		/*internal override void OnItemRemoving(object item)
		{
			ListView instance = base.Context.Instance as ListView;
			if (instance != null)
			{
				ColumnHeaderEx column = item as ColumnHeaderEx;
				if (column != null)
				{
					IComponentChangeService service = base.GetService(typeof(IComponentChangeService)) as IComponentChangeService;
					PropertyDescriptor member = null;
					if (service != null)
					{
						member = TypeDescriptor.GetProperties(base.Context.Instance)["Columns"];
						service.OnComponentChanging(base.Context.Instance, member);
					}
					instance.Columns.Remove(column);
					if ((service != null) && (member != null))
					{
						service.OnComponentChanged(base.Context.Instance, member, null, null);
					}
				}
			}
		}*/

		protected override object SetItems(object editValue, object[] value)
		{
			if (editValue != null)
			{
				XColumnHeaderCollection headers = editValue as XColumnHeaderCollection;
				if (headers != null)
				{
					headers.Clear();
					XColumnHeader[] destinationArray = new XColumnHeader[value.Length];
					Array.Copy(value, 0, destinationArray, 0, value.Length);
					headers.AddRange(destinationArray);
				}
			}
			return editValue;
		}
	}

	public partial class XListView : Control
	{
		private readonly static Size defaultSize = new Size(0x79, 0x61);

		private System.Collections.Specialized.BitVector32 listViewState;
		private ImageList imageListLarge, imageListSmall, imageListState, imageListColumn, imageListGroup;
		private XColumnHeaderCollection columns;

		public XListView()
		{
			base.SetStyle(ControlStyles.UserPaint, false);
			base.SetStyle(ControlStyles.StandardClick, false);
			base.SetStyle(ControlStyles.UseTextForAccessibility, false);
			base.SetBounds(0, 0, defaultSize.Width, defaultSize.Height);
		}

		public IList<XColumnHeader> Columns { get { return columns; } }

		protected override void CreateHandle()
		{
			if (!base.RecreatingHandle)
			{
				IntPtr userCookie = NativeMethods.ThemingScope.Activate();
				try
				{
					NativeMethods.InitCommonControlsEx(NativeMethods.CommonControlClass.ListView);
				}
				finally
				{
					NativeMethods.ThemingScope.Deactivate(userCookie);
				}
			}
			base.CreateHandle();
			if (this.BackgroundImage != null)
			{
				this.SetBackgroundImage();
			}
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (this.imageListSmall != null)
				{
					this.imageListSmall.Disposed -= new EventHandler(this.DetachImageList);
					this.imageListSmall = null;
				}
				if (this.imageListLarge != null)
				{
					this.imageListLarge.Disposed -= new EventHandler(this.DetachImageList);
					this.imageListLarge = null;
				}
				if (this.imageListState != null)
				{
					this.imageListState.Disposed -= new EventHandler(this.DetachImageList);
					this.imageListState = null;
				}
				if (this.columnHeaders != null)
				{
					for (int i = this.columnHeaders.Length - 1; i >= 0; i--)
					{
						this.columnHeaders[i].OwnerListview = null;
						this.columnHeaders[i].Dispose();
					}
					this.columnHeaders = null;
				}
				this.Items.Clear();
				if (this.odCacheFontHandleWrapper != null)
				{
					this.odCacheFontHandleWrapper.Dispose();
					this.odCacheFontHandleWrapper = null;
				}
				if (!string.IsNullOrEmpty(this.backgroundImageFileName) || (this.bkImgFileNames != null))
				{
					new FileIOPermission(PermissionState.Unrestricted).Assert();
					try
					{
						FileInfo info;
						if (!string.IsNullOrEmpty(this.backgroundImageFileName))
						{
							info = new FileInfo(this.backgroundImageFileName);
							try
							{
								info.Delete();
							}
							catch (IOException)
							{
							}
							this.backgroundImageFileName = string.Empty;
						}
						for (int j = 0; j <= this.bkImgFileNamesCount; j++)
						{
							info = new FileInfo(this.bkImgFileNames[j]);
							try
							{
								info.Delete();
							}
							catch (IOException)
							{
							}
						}
						this.bkImgFileNames = null;
						this.bkImgFileNamesCount = -1;
					}
					finally
					{
						PermissionSet.RevertAssert();
					}
				}
			}
			base.Dispose(disposing);
		}

		protected override bool IsInputKey(Keys keyData)
		{
			if ((keyData & Keys.Alt) != Keys.Alt)
			{
				switch ((keyData & Keys.KeyCode))
				{
					case Keys.Prior:
					case Keys.Next:
					case Keys.End:
					case Keys.Home:
						return true;
				}
				if (base.IsInputKey(keyData))
				{
					return true;
				}
				if (this.listViewState[0x4000])
				{
					switch ((keyData & Keys.KeyCode))
					{
						case Keys.Return:
						case Keys.Escape:
							return true;
					}
				}
			}
			return false;
		}

		protected override void OnBackgroundImageChanged(EventArgs e)
		{
			if (base.IsHandleCreated)
			{
				this.SetBackgroundImage();
			}
			base.OnBackgroundImageChanged(e);
		}

		protected override void OnFontChanged(EventArgs e)
		{
			base.OnFontChanged(e);
			if ((!this.VirtualMode && base.IsHandleCreated) && this.AutoArrange)
			{
				this.BeginUpdate();
				try
				{
					this.SendMessage(0x102a, -1, 0);
				}
				finally
				{
					this.EndUpdate();
				}
			}
			this.InvalidateColumnHeaders();
		}

		internal IntPtr SendMessage(NativeMethods.ListViewMessage msg, int wParam = 0, int lParam = 0)
		{
			if (this.IsHandleCreated)
				return NativeMethods.SendMessage(this.Handle, (uint)msg, wParam, lParam);
			return IntPtr.Zero;
		}

		protected override void OnHandleCreated(EventArgs e)
		{
			this.listViewState[0x400000] = false;
			this.FlipViewToLargeIconAndSmallIcon = false;
			base.OnHandleCreated(e);
			// Set CCM Version to at least 5
			if ((int)((long)this.SendMessage((NativeMethods.ListViewMessage)0x2008)) < 5)
				this.SendMessage((NativeMethods.ListViewMessage)0x2007, 5, 0);
			this.UpdateExtendedStyles();
			this.RealizeProperties();
			this.SendMessage(NativeMethods.ListViewMessage.SetBkColor, 0, ColorTranslator.ToWin32(this.BackColor));
			this.SendMessage(NativeMethods.ListViewMessage.SetTextColor, 0, ColorTranslator.ToWin32(base.ForeColor));
			this.SendMessage(NativeMethods.ListViewMessage.SetTextBkColor, 0, -1);
			if (!this.Scrollable)
			{
				int windowLong = (int)((long)NativeMethods.GetWindowLong(base.Handle, -16));
				windowLong |= 0x2000;
				NativeMethods.SetWindowLong(base.Handle, -16, (IntPtr)windowLong);
			}
			if (this.VirtualMode)
			{
				int wParam = (int)SendMessage(NativeMethods.ListViewMessage.GetCallbackMask);
				wParam |= 0xf000; // LVIS_STATEIMAGEMASK
				SendMessage(NativeMethods.ListViewMessage.SetCallbackMask, wParam);
			}
			if (this.ComctlSupportsVisualStyles)
			{
				this.SendMessage(0x108e, (int)this.viewStyle, 0);
				this.UpdateGroupView();
				if (this.groups != null)
				{
					for (int i = 0; i < this.groups.Count; i++)
					{
						this.InsertGroupNative(i, this.groups[i]);
					}
				}
				if (this.viewStyle == View.Tile)
				{
					this.UpdateTileView();
				}
			}
			this.ListViewHandleDestroyed = false;
			ListViewItem[] items = null;
			if (this.listItemsArray != null)
			{
				items = (ListViewItem[])this.listItemsArray.ToArray(typeof(ListViewItem));
				this.listItemsArray = null;
			}
			int num6 = (this.columnHeaders == null) ? 0 : this.columnHeaders.Length;
			if (num6 > 0)
			{
				int[] indices = new int[this.columnHeaders.Length];
				int index = 0;
				foreach (ColumnHeader header in this.columnHeaders)
				{
					indices[index] = header.DisplayIndex;
					this.InsertColumnNative(index++, header);
				}
				this.SetDisplayIndices(indices);
			}
			if ((this.itemCount > 0) && (items != null))
			{
				this.InsertItemsNative(0, items);
			}
			if ((this.VirtualMode && (this.VirtualListSize > -1)) && !base.DesignMode)
			{
				this.SendMessage(0x102f, this.VirtualListSize, 0);
			}
			if (num6 > 0)
			{
				this.UpdateColumnWidths(ColumnHeaderAutoResizeStyle.None);
			}
			this.ArrangeIcons(this.alignStyle);
			this.UpdateListViewItemsLocations();
			if (!this.VirtualMode)
			{
				this.Sort();
			}
			if (this.ComctlSupportsVisualStyles && (this.InsertionMark.Index > 0))
			{
				this.InsertionMark.UpdateListView();
			}
			this.savedCheckedItems = null;
			if (!this.CheckBoxes && !this.VirtualMode)
			{
				for (int j = 0; j < this.Items.Count; j++)
				{
					if (this.Items[j].Checked)
					{
						this.UpdateSavedCheckedItems(this.Items[j], true);
					}
				}
			}
		}

		protected override void OnHandleDestroyed(EventArgs e)
		{
			if (!base.Disposing && !this.VirtualMode)
			{
				int count = this.Items.Count;
				for (int i = 0; i < count; i++)
				{
					this.Items[i].UpdateStateFromListView(i, true);
				}
				if ((this.SelectedItems != null) && !this.VirtualMode)
				{
					ListViewItem[] itemArray = new ListViewItem[this.SelectedItems.Count];
					this.SelectedItems.CopyTo(itemArray, 0);
					this.savedSelectedItems = new List<ListViewItem>(itemArray.Length);
					for (int j = 0; j < itemArray.Length; j++)
					{
						this.savedSelectedItems.Add(itemArray[j]);
					}
				}
				ListViewItem[] dest = null;
				ListViewItemCollection items = this.Items;
				if (items != null)
				{
					dest = new ListViewItem[items.Count];
					items.CopyTo(dest, 0);
				}
				if (dest != null)
				{
					this.listItemsArray = new ArrayList(dest.Length);
					this.listItemsArray.AddRange(dest);
				}
				this.ListViewHandleDestroyed = true;
			}
			base.OnHandleDestroyed(e);
		}

		protected override void OnMouseHover(EventArgs e)
		{
			ListViewItem itemAt = null;
			if (this.Items.Count > 0)
			{
				Point position = Cursor.Position;
				position = base.PointToClientInternal(position);
				itemAt = this.GetItemAt(position.X, position.Y);
			}
			if ((itemAt != this.prevHoveredItem) && (itemAt != null))
			{
				this.OnItemMouseHover(new ListViewItemMouseHoverEventArgs(itemAt));
				this.prevHoveredItem = itemAt;
			}
			if (!this.hoveredAlready)
			{
				base.OnMouseHover(e);
				this.hoveredAlready = true;
			}
			base.ResetMouseEventArgs();
		}

		protected override void OnMouseLeave(EventArgs e)
		{
			this.hoveredAlready = false;
			base.OnMouseLeave(e);
		}

		protected override void OnParentChanged(EventArgs e)
		{
			base.OnParentChanged(e);
			if (base.IsHandleCreated)
			{
				this.RecreateHandleInternal();
			}
		}

		protected override void OnResize(EventArgs e)
		{
			if (((this.View == View.Details) && !this.Scrollable) && base.IsHandleCreated)
			{
				this.PositionHeader();
			}
			base.OnResize(e);
		}

		protected override void OnSystemColorsChanged(EventArgs e)
		{
			base.OnSystemColorsChanged(e);
			if (base.IsHandleCreated)
			{
				int lparam = ColorTranslator.ToWin32(this.BackColor);
				this.SendMessage(0x1001, 0, lparam);
				this.SendMessage(0x1026, 0, -1);
			}
		}

		public override string ToString()
		{
			string str = base.ToString();
			if (this.listItemsArray != null)
			{
				str = str + ", Items.Count: " + this.listItemsArray.Count.ToString(CultureInfo.CurrentCulture);
				if (this.listItemsArray.Count > 0)
				{
					string str2 = this.listItemsArray[0].ToString();
					string str3 = (str2.Length > 40) ? str2.Substring(0, 40) : str2;
					str = str + ", Items[0]: " + str3;
				}
				return str;
			}
			if (this.Items != null)
			{
				str = str + ", Items.Count: " + this.Items.Count.ToString(CultureInfo.CurrentCulture);
				if ((this.Items.Count > 0) && !this.VirtualMode)
				{
					string str4 = (this.Items[0] == null) ? "null" : this.Items[0].ToString();
					string str5 = (str4.Length > 40) ? str4.Substring(0, 40) : str4;
					str = str + ", Items[0]: " + str5;
				}
			}
			return str;
		}

		protected override void WndProc(ref Message m)
		{
			switch (m.Msg)
			{
				case 0x4e:
					if (!this.WmNotify(ref m))
					{
						break;
					}
					return;

				case 0x113:
					if ((((int)((long)m.WParam)) != 0x30) || !this.ComctlSupportsVisualStyles)
					{
						base.WndProc(ref m);
					}
					return;

				case 7:
					base.WndProc(ref m);
					if ((!base.RecreatingHandle && !this.ListViewHandleDestroyed) && ((this.FocusedItem == null) && (this.Items.Count > 0)))
					{
						this.Items[0].Focused = true;
					}
					return;

				case 15:
					base.WndProc(ref m);
					base.BeginInvoke(new MethodInvoker(this.CleanPreviousBackgroundImageFiles));
					return;

				case 0x200:
					if ((this.listViewState[0x100000] && !this.listViewState[0x80000]) && (Control.MouseButtons == MouseButtons.None))
					{
						this.OnMouseUp(new MouseEventArgs(this.downButton, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0));
						this.listViewState[0x80000] = true;
					}
					base.CaptureInternal = false;
					base.WndProc(ref m);
					return;

				case 0x201:
					this.ItemCollectionChangedInMouseDown = false;
					this.WmMouseDown(ref m, MouseButtons.Left, 1);
					this.downButton = MouseButtons.Left;
					return;

				case 0x202:
				case 0x205:
				case 520:
					{
						NativeMethods.LVHITTESTINFO lvhi = new NativeMethods.LVHITTESTINFO();
						int indexOfClickedItem = this.GetIndexOfClickedItem(lvhi);
						if ((!base.ValidationCancelled && this.listViewState[0x40000]) && (indexOfClickedItem != -1))
						{
							this.listViewState[0x40000] = false;
							this.OnDoubleClick(EventArgs.Empty);
							this.OnMouseDoubleClick(new MouseEventArgs(this.downButton, 2, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0));
						}
						if (!this.listViewState[0x80000])
						{
							this.OnMouseUp(new MouseEventArgs(this.downButton, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0));
							this.listViewState[0x100000] = false;
						}
						this.ItemCollectionChangedInMouseDown = false;
						this.listViewState[0x80000] = true;
						base.CaptureInternal = false;
						return;
					}
				case 0x203:
					this.ItemCollectionChangedInMouseDown = false;
					base.CaptureInternal = true;
					this.WmMouseDown(ref m, MouseButtons.Left, 2);
					return;

				case 0x204:
					this.WmMouseDown(ref m, MouseButtons.Right, 1);
					this.downButton = MouseButtons.Right;
					return;

				case 0x206:
					this.WmMouseDown(ref m, MouseButtons.Right, 2);
					return;

				case 0x207:
					this.WmMouseDown(ref m, MouseButtons.Middle, 1);
					this.downButton = MouseButtons.Middle;
					return;

				case 0x209:
					this.WmMouseDown(ref m, MouseButtons.Middle, 2);
					return;

				case 0x2a1:
					if (!this.HoverSelection)
					{
						this.OnMouseHover(EventArgs.Empty);
						return;
					}
					base.WndProc(ref m);
					return;

				case 0x2a3:
					this.prevHoveredItem = null;
					base.WndProc(ref m);
					return;

				case 0x317:
					this.WmPrint(ref m);
					return;

				case 0x204e:
					this.WmReflectNotify(ref m);
					return;
			}
			base.WndProc(ref m);
		}

		private void SetBackgroundImage()
		{
			Application.OleRequired();
			NativeMethods.LVBKIMAGE lParam = new NativeMethods.LVBKIMAGE();
			lParam.xOffset = 0;
			lParam.yOffset = 0;
			string backgroundImageFileName = this.backgroundImageFileName;
			if (this.BackgroundImage != null)
			{
				EnvironmentPermission perm = new EnvironmentPermission(EnvironmentPermissionAccess.Read, "TEMP");
				FileIOPermission permission2 = new FileIOPermission(PermissionState.Unrestricted);
				PermissionSet set = new PermissionSet(PermissionState.Unrestricted);
				set.AddPermission(perm);
				set.AddPermission(permission2);
				set.Assert();
				try
				{
					string tempPath = Path.GetTempPath();
					StringBuilder sb = new StringBuilder(0x400);
					UnsafeNativeMethods.GetTempFileName(tempPath, this.GenerateRandomName(), 0, sb);
					this.backgroundImageFileName = sb.ToString();
					this.BackgroundImage.Save(this.backgroundImageFileName, ImageFormat.Bmp);
				}
				finally
				{
					PermissionSet.RevertAssert();
				}
				lParam.pszImage = this.backgroundImageFileName;
				lParam.cchImageMax = this.backgroundImageFileName.Length + 1;
				lParam.ulFlags = 2;
				if (this.BackgroundImageTiled)
				{
					lParam.ulFlags |= 0x10;
				}
				else
				{
					lParam.ulFlags = lParam.ulFlags;
				}
			}
			else
			{
				lParam.ulFlags = 0;
				this.backgroundImageFileName = string.Empty;
			}
			UnsafeNativeMethods.SendMessage(new HandleRef(this, base.Handle), NativeMethods.LVM_SETBKIMAGE, 0, lParam);
			if (!string.IsNullOrEmpty(backgroundImageFileName))
			{
				if (this.bkImgFileNames == null)
				{
					this.bkImgFileNames = new string[8];
					this.bkImgFileNamesCount = -1;
				}
				if (this.bkImgFileNamesCount == 7)
				{
					this.DeleteFileName(this.bkImgFileNames[0]);
					this.bkImgFileNames[0] = this.bkImgFileNames[1];
					this.bkImgFileNames[1] = this.bkImgFileNames[2];
					this.bkImgFileNames[2] = this.bkImgFileNames[3];
					this.bkImgFileNames[3] = this.bkImgFileNames[4];
					this.bkImgFileNames[4] = this.bkImgFileNames[5];
					this.bkImgFileNames[5] = this.bkImgFileNames[6];
					this.bkImgFileNames[6] = this.bkImgFileNames[7];
					this.bkImgFileNames[7] = null;
					this.bkImgFileNamesCount--;
				}
				this.bkImgFileNamesCount++;
				this.bkImgFileNames[this.bkImgFileNamesCount] = backgroundImageFileName;
				this.Refresh();
			}
		}

		public override Color BackColor
		{
			get
			{
				if (this.ShouldSerializeBackColor())
					return base.BackColor;
				return SystemColors.Window;
			}
			set
			{
				base.BackColor = value;
				if (base.IsHandleCreated)
					this.SendMessage(0x1001, 0, ColorTranslator.ToWin32(this.BackColor));
			}
		}

		[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
		public override ImageLayout BackgroundImageLayout
		{
			get { return base.BackgroundImageLayout; }
			set { base.BackgroundImageLayout = value; }
		}

		protected override CreateParams CreateParams
		{
			[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
			get
			{
				CreateParams createParams = base.CreateParams;
				createParams.ClassName = "SysListView32";
				if (base.IsHandleCreated)
				{
					int windowLong = (int)((long)NativeMethods.GetWindowLong(base.Handle, -16));
					createParams.Style |= windowLong & 0x300000;
				}
				createParams.Style |= NativeMethods.ListViewStyle.ShareImageLists;
				switch (this.alignStyle)
				{
					case ListViewAlignment.Left:
						createParams.Style |= 0x800;
						break;

					case ListViewAlignment.Top:
						createParams.Style = createParams.Style;
						break;
				}
				if (this.AutoArrange)
				{
					createParams.Style |= 0x100;
				}
				switch (this.borderStyle)
				{
					case BorderStyle.FixedSingle:
						createParams.Style |= 0x800000;
						break;

					case BorderStyle.Fixed3D:
						createParams.ExStyle |= 0x200;
						break;
				}
				switch (this.headerStyle)
				{
					case ColumnHeaderStyle.None:
						createParams.Style |= 0x4000;
						break;

					case ColumnHeaderStyle.Nonclickable:
						createParams.Style |= 0x8000;
						break;
				}
				if (this.LabelEdit)
				{
					createParams.Style |= 0x200;
				}
				if (!this.LabelWrap)
				{
					createParams.Style |= 0x80;
				}
				if (!this.HideSelection)
				{
					createParams.Style |= 8;
				}
				if (!this.MultiSelect)
				{
					createParams.Style |= 4;
				}
				if (this.listItemSorter == null)
				{
					switch (this.sorting)
					{
						case SortOrder.Ascending:
							createParams.Style |= 0x10;
							break;

						case SortOrder.Descending:
							createParams.Style |= 0x20;
							break;
					}
				}
				if (this.VirtualMode)
				{
					createParams.Style |= 0x1000;
				}
				if (this.viewStyle != View.Tile)
				{
					createParams.Style |= this.viewStyle;
				}
				if ((this.RightToLeft == RightToLeft.Yes) && this.RightToLeftLayout)
				{
					createParams.ExStyle |= 0x400000;
					createParams.ExStyle &= -28673;
				}
				return createParams;
			}
		}

		protected override Size DefaultSize
		{
			get { return defaultSize; }
		}

		protected override bool DoubleBuffered
		{
			get
			{
				return base.DoubleBuffered;
			}
			set
			{
				if (this.DoubleBuffered != value)
				{
					base.DoubleBuffered = value;
					this.UpdateExtendedStyles();
				}
			}
		}

		public override Color ForeColor
		{
			get
			{
				if (this.ShouldSerializeForeColor())
				{
					return base.ForeColor;
				}
				return SystemColors.WindowText;
			}
			set
			{
				base.ForeColor = value;
				if (base.IsHandleCreated)
				{
					this.SendMessage(0x1024, 0, ColorTranslator.ToWin32(this.ForeColor));
				}
			}
		}

		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), Bindable(false)]
		public override string Text
		{
			get { return base.Text; }
			set { base.Text = value; }
		}
 
	}
}
